package com.cambright.lotusroot
{
	import com.cambright.Enumerator;
	
	import flash.display.Loader;
	import flash.display.LoaderInfo;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.ByteArray;
	import flash.utils.clearInterval;
	import flash.utils.setInterval;
	
	import nochump.util.zip.ZipEntry;
	import nochump.util.zip.ZipFile;
	
	internal class $Library
	{
		static private const _HUB:$Library = new $Library();
		static public function get HUB():$Library
		{
			return _HUB;
		}
		
		private var _fileVec:Vector.<File> = new Vector.<File>();
		
		private var _intervalID:int;
		
		private var _fileEnumerator:Enumerator;
		private var _loader:Loader;
		
		public function add(file:File):void
		{
			_fileVec.push(file);
		}
		
		public function load():void
		{
			_fileEnumerator = new Enumerator(_fileVec);
			_intervalID = setInterval(_load, 1000);
		}
		
		private function _load():void
		{
			clearInterval(_intervalID);
			
			if(_fileEnumerator.next())
			{
				var file:File = _fileEnumerator.current;
				_loader = new Loader();
				_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, _onProgress);
				var context:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
				context.allowCodeImport = true;
				
				if(file.extension == "swc")
				{
					var fileStream:FileStream = new FileStream();
					fileStream.open(file, FileMode.READ);
					var byteArray:ByteArray = new ByteArray();
					fileStream.readBytes(byteArray, 0, fileStream.bytesAvailable);
					fileStream.close();
					
					var zipFile:ZipFile = new ZipFile(byteArray);
					var zipEntry:ZipEntry = zipFile.getEntry("library.swf");
					byteArray = zipFile.getInput(zipEntry);
					_loader.loadBytes(byteArray, context);
				}
				else if(file.extension == "swf")
				{
					var request:URLRequest = new URLRequest(file.url);
					_loader.load(request, context);
				}
			}
			else _intervalID = setInterval(_complete, 100);
		}
		
		private function _onProgress(event:ProgressEvent):void
		{
			if(event.bytesLoaded == event.bytesTotal)
				_intervalID = setInterval(_checkContent, 20);
		}
		
		private function _checkContent():void
		{
			if(_loader.content != null)
				_onComplete();
		}
		
		private function _onComplete():void
		{
			clearInterval(_intervalID);
			
			var loaderInfo:LoaderInfo = _loader.contentLoaderInfo;
			loaderInfo.removeEventListener(ProgressEvent.PROGRESS, _onProgress);
			_loader.unloadAndStop(true);
			_loader = null;
			
			_intervalID = setInterval(_load, 100);
		}
		
		private function _complete():void
		{
			clearInterval(_intervalID);
			
			_fileEnumerator.dispose();
			_fileEnumerator = null;
			
			Application.$CURRENT.$step();
		}
	}
}